<?php

/**
 * @copyright (c) 2016
 * @brief 商品管理类库
 * @author jumark
 * @date 2016/7/21
 * @version 1.0
 */

namespace Partner\Model;

use Think\IFilter;
use Think\ITime;
use Think\JSON;

class Goods {

    //算账类库
    private static $countsumInstance = null;
    //商户ID
    public $seller_id = '';

    //构造函数
    public function __construct($seller_id = '') {
        $this->seller_id = $seller_id;
    }

    /**
     * 获取商品价格
     * @param int $goods_id 商品ID
     * @param float $sell_price 商品销售价
     */
    public static function price($goods_id, $sell_price) {
        if (self::$countsumInstance == null) {
            self::$countsumInstance = new CountSum();
        }
        $price = self::$countsumInstance->getGroupPrice($goods_id);
        return $price ? $price : $sell_price;
    }

    /**
     * 生成商品货号
     * @return string 货号
     */
    public static function createGoodsNo() {
        //$config = new Config('site_config');
        //return $config->goods_no_pre . time() . rand(10, 99);
        return 'SD' . time() . rand(10, 99);
    }

    /**
     * @brief 修改商品数据
     * @param int $id 商品ID
     * @param array $paramData 商品所需数据
     */
    public function update($id, $paramData) {
        $postData = array();
        $nowDataTime = ITime::getDateTime();

        $goodsAttrData = array();
        foreach ($paramData as $key => $val) {
            $postData[$key] = $val;

            //数据过滤分组
            if (strpos($key, 'attr_id_') !== false) {
                $goodsAttrData[ltrim($key, 'attr_id_')] = IFilter::act($val);
            } else if ($key == 'content') {
                $goodsUpdateData['content'] = IFilter::addSlash($val);
            } else if ($key[0] != '_') {
                $goodsUpdateData[$key] = IFilter::act($val);
            }
        }

        //商家发布商品默认设置
        if ($this->seller_id) {
            $goodsUpdateData['seller_id'] = $this->seller_id;
        }

        //是否存在货品
        $goodsUpdateData['spec_array'] = '';
        if (isset($postData['_spec_array'])) {
            //生成goods中的spec_array字段数据
            $goods_spec_array = array();
            foreach ($postData['_spec_array'] as $key => $val) {
                foreach ($val as $v) {
                    $tempSpec = JSON::decode($v);
                    if (!isset($goods_spec_array[$tempSpec['id']])) {
                        $goods_spec_array[$tempSpec['id']] = array('id' => $tempSpec['id'], 'name' => $tempSpec['name'], 'type' => $tempSpec['type'], 'value' => array());
                    }
                    $goods_spec_array[$tempSpec['id']]['value'][] = $tempSpec['value'];
                }
            }
            foreach ($goods_spec_array as $key => $val) {
                $val['value'] = array_unique($val['value']);
                $goods_spec_array[$key]['value'] = join(',', $val['value']);
            }
            $goodsUpdateData['spec_array'] = JSON::encode($goods_spec_array);
        }

        $goodsUpdateData['goods_no'] = isset($postData['_goods_no']) ? current($postData['_goods_no']) : '';
        $goodsUpdateData['store_nums'] = array_sum($postData['_store_nums']);
        $goodsUpdateData['market_price'] = isset($postData['_market_price']) ? current($postData['_market_price']) : 0;
        $goodsUpdateData['sell_price'] = isset($postData['_sell_price']) ? current($postData['_sell_price']) : 0;
        $goodsUpdateData['cost_price'] = isset($postData['_cost_price']) ? current($postData['_cost_price']) : 0;
        $goodsUpdateData['weight'] = isset($postData['_weight']) ? current($postData['_weight']) : 0;

        //处理商品
        $goodsDB = M('goods');
        if ($id) {
            $goodsUpdateData['id'] = $id;
            if ($this->seller_id) {
                $goodsUpdateData['seller_id'] = $this->seller_id;
            }

            if ($goodsDB->save($goodsUpdateData) === false) {
                die("更新商品错误");
            }
        } else {
            $goodsUpdateData['create_time'] = $nowDataTime;
            $id = $goodsDB->add($goodsUpdateData);
        }

        //处理商品属性
        $goodsAttrDB = M('goods_attribute');
        $goodsAttrDB->where(array('goods_id' => $id))->delete();
        if ($goodsUpdateData['model_id'] > 0 && isset($goodsAttrData) && $goodsAttrData) {
            foreach ($goodsAttrData as $key => $val) {
                $attrData = array(
                    'goods_id' => $id,
                    'model_id' => $goodsUpdateData['model_id'],
                    'attribute_id' => $key,
                    'attribute_value' => is_array($val) ? join(',', $val) : $val
                );
                $goodsAttrDB->add($attrData);
            }
        }

        //是否存在货品
        $productsDB = M('products');
        $productsDB->where(array('goods_id' => $id))->delete();
        if (isset($postData['_spec_array'])) {
            $productIdArray = array();

            //创建货品信息
            foreach ($postData['_goods_no'] as $key => $rs) {
                $productsData = array(
                    'goods_id' => $id,
                    'products_no' => $postData['_goods_no'][$key],
                    'store_nums' => $postData['_store_nums'][$key],
                    'market_price' => $postData['_market_price'][$key],
                    'sell_price' => $postData['_sell_price'][$key],
                    'cost_price' => $postData['_cost_price'][$key],
                    'weight' => $postData['_weight'][$key],
                    'spec_array' => "[" . join(',', $postData['_spec_array'][$key]) . "]"
                );
                $productIdArray[$key] = $productsDB->add($productsData);
            }
        }

        //处理商品分类
        $categoryDB = M('category_extend');
        $categoryDB->where(array('goods_id' => $id))->delete();
        if (isset($postData['_goods_category']) && $postData['_goods_category']) {
            foreach ($postData['_goods_category'] as $item) {
                $categoryData = array(
                    'goods_id' => $id,
                    'category_id' => $item
                );
                $categoryDB->add($categoryData);
            }
        }


        //处理商品关键词
        // keywords::add($goodsUpdateData['search_words']);
        //处理商品图片
        $photoRelationDB = M('goods_photo_relation');
        $photoRelationDB->where(array('goods_id' => $id))->delete();
        $postData['_imgList'] = trim($postData['_imgList'], ',');
        if (isset($postData['_imgList']) && $postData['_imgList']) {
            $postData['_imgList'] = explode(",", $postData['_imgList']);
            $postData['_imgList'] = array_filter($postData['_imgList']);
            if ($postData['_imgList']) {
                $photoDB = M('goods_photo');
                foreach ($postData['_imgList'] as $key => $val) {
                    $photoPic = $photoDB->where(array('img' => $val))->field('id')->find();
                    if ($photoPic) {
                        $photoRelationDB->add(array('goods_id' => $id, 'photo_id' => $photoPic['id']));
                    }
                }
            }
        }
        return $id;
    }

    /**
     * @brief 删除与商品相关表中的数据
     */
    public function del($goods_id) {
        $goodsWhere = " id = '{$goods_id}' ";
        if ($this->seller_id) {
            $goodsWhere .= " and seller_id = " . $this->seller_id;
        }

        //图片清理
        $tb_photo_relation = new IModel('goods_photo_relation');
        $photoMD5Data = $tb_photo_relation->query('goods_id = ' . $goods_id);

        $tb_photo = new IModel('goods_photo');
        foreach ($photoMD5Data as $key => $md5) {
            //图片是否被其他商品共享占用
            $isUserd = $tb_photo_relation->getObj('photo_id = "' . $md5['photo_id'] . '" and goods_id != ' . $goods_id);
            if (!$isUserd) {
                $imgData = $tb_photo->getObj('id = "' . $md5['photo_id'] . '"');
                isset($imgData['img']) ? IFile::unlink($imgData['img']) : "";
                $tb_photo->del('id = "' . $md5['photo_id'] . '"');
            }
        }
        $tb_photo_relation->del('goods_id = ' . $goods_id);

        //删除商品表
        $tb_goods = new IModel('goods');
        $goodsRow = $tb_goods->getObj($goodsWhere, "content");
        if (isset($goodsRow['content']) && $goodsRow['content']) {
            
        }
        $tb_goods->del($goodsWhere);
    }

    /**
     * 获取编辑商品所有数据
     * @param int $id 商品ID
     */
    public function edit($id) {
        $id = IFilter::act($id, 'int');
        $goodsWhere = array(
            'id' => $id
        );
        if ($this->seller_id) {
            $goodsWhere['seller_id'] = $this->seller_id;
        }

        //获取商品
        $obj_goods = M('goods');
        $goods_info = $obj_goods->where($goodsWhere)->find();

        if (!$goods_info) {
            return null;
        }

        //赋值到FORM用于渲染
        $data = array('form' => $goods_info);

        //获取货品
        $productObj = M('products');
        $product_info = $productObj->where(array('goods_id' => $id))->select();
        if ($product_info) {
            $data['product'] = $product_info;
        }

        //相册
        $tb_goods_photo = M('goods_photo_relation as ghr');
        $goods_photo_join = 'left join sm_goods_photo as gh on ghr.photo_id=gh.id';
        $goods_photo_fields = 'gh.img';
        $goods_photo_where = 'ghr.goods_id=' . $goods_info['id'];
        $goods_photo_order = 'ghr.id asc';
        $data['goods_photo'] = $tb_goods_photo->join($goods_photo_join)->where($goods_photo_where)->field($goods_photo_fields)->order($goods_photo_order)->select();

        //扩展基本属性
        $goodsAttr = M('goods_attribute');
        $goodsAttr_where = array(
            'goods_id' => $goods_info['id'],
            "attribute_id != ''"
        );
        $attrInfo = $goodsAttr->where($goodsAttr_where)->select();
        if ($attrInfo) {
            foreach ($attrInfo as $item) {
                //key：属性名；val：属性值,多个属性值以","分割
                $data['goods_attr'][$item['attribute_id']] = $item['attribute_value'];
            }
        }

        //商品分类
        $categoryExtend = M('category_extend');
        $categoryExtend_where = array(
            'goods_id' => $goods_info['id']
        );

        $tb_goods_photo_fields = 'category_id';
        $cateData = $categoryExtend->where($categoryExtend_where)->field($tb_goods_photo_fields)->select();
        if ($cateData) {
            foreach ($cateData as $item) {
                $data['goods_category'][] = $item['category_id'];
            }
        }
        return $data;
    }

    /**
     * @param
     * @return array
     * @brief 无限极分类递归函数
     */
    public static function sortdata($catArray, $id = 0, $prefix = '') {
        static $formatCat = array();
        static $floor = 0;

        foreach ($catArray as $key => $val) {
            if ($val['parent_id'] == $id) {
                $str = self::nstr($prefix, $floor);
                $val['name'] = $str . $val['name'];

                $val['floor'] = $floor;
                $formatCat[] = $val;

                unset($catArray[$key]);

                $floor++;
                self::sortdata($catArray, $val['id'], $prefix);
                $floor--;
            }
        }
        return $formatCat;
    }

    /**
     * @brief 根据商品分类的父类ID进行数据归类
     * @param array $categoryData 商品category表的结构数组
     * @return array
     */
    public static function categoryParentStruct($categoryData) {
        $result = array();
        foreach ($categoryData as $key => $val) {
            if (isset($result[$val['parent_id']]) && is_array($result[$val['parent_id']])) {
                $result[$val['parent_id']][] = $val;
            } else {
                $result[$val['parent_id']] = array($val);
            }
        }
        return $result;
    }

    /**
     * @brief 计算商品的价格区间
     * @param $min          最小价格
     * @param $max          最大价格
     * @param $showPriceNum 展示分组最大数量
     * @return array        价格区间分组
     */
    public static function getGoodsPrice($min, $max, $showPriceNum = 5) {
        $goodsPrice = array("min" => $min, "max" => $max);
        if ($goodsPrice['min'] == null && $goodsPrice['max'] == null) {
            return array();
        }

        if ($goodsPrice['min'] <= 0) {
            $minPrice = 1;
            $result = array('0-' . $minPrice);
        } else {
            $minPrice = ceil($goodsPrice['min']);
            $result = array('1-' . $minPrice);
        }

        //商品价格计算
        $perPrice = ceil(($goodsPrice['max'] - $minPrice) / ($showPriceNum - 1));

        if ($perPrice > 0) {
            for ($addPrice = $minPrice + 1; $addPrice < $goodsPrice['max'];) {
                $stepPrice = $addPrice + $perPrice;
                $stepPrice = substr(intval($stepPrice), 0, 1) . str_repeat('9', (strlen(intval($stepPrice)) - 1));
                $result[] = $addPrice . '-' . $stepPrice;
                $addPrice = $stepPrice + 1;
            }
        }
        return $result;
    }

    //处理商品列表显示缩进
    public static function nstr($str, $num = 0) {
        $return = '';
        for ($i = 0; $i < $num; $i++) {
            $return .= $str;
        }
        return $return;
    }

    /**
     * @brief  根据分类ID获取其全部父分类数据(自下向上的获取数据)
     * @param  int   $catId  分类ID
     * @return array $result array(array(父分类1_ID => 父分类2_NAME),....array(子分类ID => 子分类NAME))
     */
    public static function catRecursion($catId) {
        $result = array();
        $catDB = new IModel('category');
        $catRow = $catDB->getObj("id = '{$catId}'");
        while (true) {
            if ($catRow) {
                array_unshift($result, array('id' => $catRow['id'], 'name' => $catRow['name']));
                $catRow = $catDB->getObj('id = ' . $catRow['parent_id']);
            } else {
                break;
            }
        }
        return $result;
    }

    /**
     * @brief 优先获取子分类，如果为空再获取其兄弟分类
     * @param int $catId 分类ID
     * @return array
     */
    public static function catTree($catId) {
        $result = array();
        $catDB = new IModel('category');
        $childList = $catDB->query("parent_id = '{$catId}'", "*", "sort asc");
        if (!$childList) {
            $catRow = $catDB->getObj("id = '{$catId}'");
            $childList = $catDB->query('parent_id = ' . $catRow['parent_id'], "*", "sort asc");
        }
        return $childList;
    }

    /**
     * @brief 获取子分类可以无限递归获取子分类
     * @param int $catId 分类ID
     * @param int $level 层级数
     * @return string 所有分类的ID拼接字符串
     */
    public static function catChild($catId, $level = 1) {
        if ($level == 0) {
            return $catId;
        }

        $temp = array();
        $result = array($catId);
        $catDB = new IModel('category');

        while (true) {
            $id = current($result);
            if (!$id) {
                break;
            }
            $temp = $catDB->query('parent_id = ' . $id);
            foreach ($temp as $key => $val) {
                if (!in_array($val['id'], $result)) {
                    $result[] = $val['id'];
                }
            }
            next($result);
        }
        return join(',', $result);
    }

    /**
     * @brief 返回商品状态
     * @param int $is_del 商品状态
     * @return string 状态文字
     */
    public static function statusText($is_del) {
        $date = array('0' => '上架', '1' => '删除', '2' => '下架', '3' => '等审');
        return isset($date[$is_del]) ? $date[$is_del] : '';
    }

    public static function getGoodsCategory($goods_id) {

        $gcQuery = M('category_extend as ce');
        $join = "left join sm_category as c on c.id = ce.category_id";
        $where = "ce.goods_id = '{$goods_id}'";
        $fields = 'c.name';

        $gcList = $gcQuery->join($join)->where($where)->field($fields)->select();
        $strCategoryNames = '';
        foreach ($gcList as $val) {
            $strCategoryNames .= '[' . $val['name'] . ']';
        }
        unset($gcQuery, $gcList);
        return $strCategoryNames;
    }

    /**
     * @brief 返回检索条件相关信息
     * @param int $search 条件数组
     * @return array 查询条件（$join,$where）数据组
     */
    public static function getSearchCondition($search, $seller_id = '') {
        $join = array('left join sm_brand as b on go.brand_id = b.id');
        $where = array();
        if ($seller_id) {
            $where[] = "go.seller_id = " . $seller_id;
        }

        //条件筛选处理
        if (isset($search['name']) && isset($search['keywords'])) {
            $name = IFilter::act($search['name'], 'string');
            $keywords = IFilter::act($search['keywords'], 'string');
            if ($keywords) {
                $where[] = $name . " like '%" . $keywords . "%'";
            }
        }
        if (isset($search['brand_id']) && !empty($search['brand_id'])) {
            $brand_id = IFilter::act($search['brand_id'], 'int');
            $where[] = "go.brand_id = " . $brand_id;
        }

        if (isset($search['category_id'])) {
            $category_id = IFilter::act($search['category_id'], 'int');
            if (0 < $category_id) {
                $join[] = "left join sm_category_extend as ce on ce.goods_id = go.id";
                $where[] = "ce.category_id = " . $category_id;
            }
        }

        if (isset($search['is_del']) && $search['is_del'] !== '') {
            $is_del = IFilter::act($search['is_del'], 'int');
            $where[] = "go.is_del = " . $is_del;
        } else {
            $where[] = "go.is_del != 1";
        }

        $results = array(join("  ", $join), join(" and ", $where));
        unset($join, $where);
        return $results;
    }

    /**
     * @brief 获取运算符号
     * @param string $type 	运算类型 1-增加 2-减少
     * @return string 		运算符号
     */
    protected function getOperator($type) {
        return '2' == $type ? '-' : '+';
    }

}